const distanceX = 904; //1383
const distanceY = 468; //1257
const firstCarX = 480; //生涯列表771,赛事列表880
const firstCarY = 790;

var bronze = {
    point: {
        x: 1980,
        y: 300
    },
    cars: {
        nums: [12, 10, 9, 8, 7]
    }
};

var silver = {
    point: {
        x: 2160,
        y: 300
    },
    cars: {
        nums: [14, 13, 12, 11, 9, 8, 7]
    }
};

var gold = {
    point: {
        x: 2340,
        y: 300
    },
    cars: {
        nums: [16, 15, 14, 13, 12, 11]
    }
};

var platinum = {
    point: {
        x: 2520,
        y: 300
    },
    cars: {
        nums: [13, 12, 11, 10, 9, 7]
    }
};

var legend = {
    point: {
        x: 2700,
        y: 300
    },
    cars: {
        nums: [13, 12, 11, 9, 8, 7, 5, 4, 3]
    }
};

var rank = platinum;
var scoreRank = null;
var isStarted = false;

mainEntrence();

// 程序主入口
function mainEntrence() {
    deviceInfo();
    eventListener();
    sleep(2000);

    // 运行主函数
    main();
    // isRunStart();

}


function eventListener() {
    threads.start(function() {
        // 启用按键监听
        events.observeKey();
        // 监听音量上键按下
        events.onKeyDown("volume_down", function(event) {
            toastLog("程序手动退出");
            threads.shutDownAll();
            exit();
        });
    });
}


function deviceInfo() {
    auto();
    if (!requestScreenCapture()) {
        toast('请求截图失败，程序结束');
        exit();
    }
    // 调整屏幕亮度
    device.setBrightness(0);
}

function main() {
    toast("开始运行");
    homePage();
    startMp();
}

function homePage() {
    var mpBtn = getPointColor(captureScreen(), 1600, 1300);
    if (!colors.isSimilar(mpBtn, "#ffffffff", 5)) {
        click(1600, 1300);
        sleep(1000);
    }
    click(1800, 500);
    sleep(2500);
}

function startMp() {
    click(1400, 1300);
    sleep(4000);
    if (scoreRank == null) {
        checkScoreRank();
    }
    toast("开始选车");
    rank = scoreRank;
    selectInCarPage();
    runUtilEnd();
}

//检查当前最高段位
function checkScoreRank() {
    var finish = false
    scoreRank = legend;
    do {
        click(scoreRank.point.x, scoreRank.point.y);
        sleep(2000);
        click(firstCarX, firstCarY);
        sleep(2500);
        var upgradeBtn = getPointColor(captureScreen(), 260, 1300);
        if (colors.isSimilar(upgradeBtn, "#ffffffff")) {
            finish = true;
        } else {
            if (scoreRank == legend) {
                scoreRank = platinum;
            } else if (scoreRank == platinum) {
                scoreRank = gold;
            } else if (scoreRank == gold) {
                scoreRank = silver;
            } else if (scoreRank == silver) {
                scoreRank = bronze;
                finish = true;
            }
        }
        back();
        sleep(3000);
    } while (!finish);
}

function selectInCarPage() {
    // 选车
    chooseModeAndCar();
    sleep(2500);
    checkTouchDrive();
    // 开始
    click(2400, 1280);
    checkConnect();
}

function checkTouchDrive() {
    sleep(1000);
    var tdPoint = findColor(captureScreen(), "#ffc0f814", {
        region: [2700, 1060, 120, 100],
        threshold: 10
    });
    toast(tdPoint);
    if (!tdPoint) {
        toast("打开自动驾驶");
        click(2700, 1100);
        sleep(2000);
    }
}

function checkConnect() {
    var connected = false;
    var times = 120;
    do {
        sleep(1000);
        var img = captureScreen();

        //出现赛道信息，视为开始
        var siteInfo = getPointColor(img, 300, 190);
        connected = colors.equals(topBg, "#ffffffff",10);

        var errorClose = getPointColor(img, 2500, 400);
        if (colors.isSimilar(errorClose, "#ffff0054", 6)) {
            click(2500, 400);
            sleep(3000);
            toast("重连选车");
            selectInCarPage();
            return;
        }

        //超时重新选车
        if(times == 0){
            back();
            sleep(3000);
            toast("重连选车");
            selectInCarPage();
            return;
        }else{
            times = times - 1;
        }
    } while (!connected);
}

function runUtilEnd() {
    toast("开始");
    var isEnd = false;
    do {
        sleep(1000);
        var continueBtn = getPointColor(captureScreen(), 2380, 1260);
        if (colors.isSimilar(continueBtn, "#ffc3fb12")) {
            isEnd = true;
        } else {
            swipe(1960, 720, 1000, 720, 300);
            swipe(1960, 720, 1000, 720, 300);
            click(2490, 1120);
        }
    } while (!isEnd);
    afterRun();
}

function chooseModeAndCar() {

    click(rank.point.x, rank.point.y);
    sleep(1500);

    var selected = false;
    var swiped = false;

    var numArray = rank.cars.nums;
    for (i = 0; i < numArray.length; i++) {
        var num = 0;

        if (numArray[i] > 6 && !swiped) {
            swipe(2959, 720, 200, 720, 4000);
            sleep(1500);
            swiped = true;
            if (numArray[i] > 12) {
                if(rank == legend){
                    swipe(2480, 720, 1500, 720, 4000);
                    sleep(1500);
                    selected = selectCar(2267, firstCarY + ((num - 1) % 2) * distanceY);
                    if (selected) {
                        toast("选车完成");
                        return;
                    }
                    click(rank.point.x, rank.point.y);
                    sleep(1500);
                    swiped = false;
                    continue;
                }
                swipe(2959, 720, 200, 720, 4000);
                sleep(1500);
            }
        } else {
            if (numArray[i] <= 6 && swiped) {
                click(rank.point.x, rank.point.y);
                sleep(1500);
                swiped = false;
            }
        }

        if (swiped) {
            do {
                num = numArray[i] - 6;
            } while (num > 6)
        } else {
            num = numArray[i];
        }
        var x = firstCarX + parseInt((num - 1) / 2) * distanceX;
        var y = firstCarY + ((num - 1) % 2) * distanceY;
        selected = selectCar(x, y);
        if (selected) {
            toast("选车完成");
            return
        }
    }

    changeRank();


}

function selectCar(x, y) {
    var img = captureScreen();
    var posData = checkForResolution(x + 10, y, img);
    var oil = images.pixel(img, posData.positionX, posData.positionY);
    toast(x + "," + y + "," + colors.toString(oil));
    if (colors.isSimilar(oil, "#ffc0f814", 40)) {
        // if (colors.isSimilar(oil, "#ff9ccf25") || colors.isSimilar(oil, "#ffc8e610") || colors.isSimilar(oil, "#ffc5f011") || colors.isSimilar(oil, "#ffc0f814")) {
        click(x, y);
        return true;
    }
    return false;
}

function changeRank() {
    if (rank == legend) {
        rank = platinum;
    } else if (rank == platinum) {
        rank = gold;
    } else if (rank == gold) {
        rank = silver;
    } else if (rank == silver) {
        rank = bronze;
    }
    chooseModeAndCar();
}

function afterRun() {
    toast("跑完了");
    sleep(1000);
    clickContinue();
    sleep(4000);
    var continueBtn = getPointColor(captureScreen(), 2380, 1260);
    if (colors.isSimilar(continueBtn, "#ffc2f912", 8)) {
        clickContinue();
        sleep(4000);
        clickContinue();
        sleep(2000);
        clickContinue();
    }

    sleep(6000);

    reward();

}

function reward() {
    var startBtn = getPointColor(captureScreen(), 1300, 1300);
    if (colors.isSimilar(startBtn, "#ffc3fb12", 8)) {
        startMp();
        return;
    }
    sleep(4000);
    var receive = getPointColor(captureScreen(), 1300, 1050);
    // toast(colors.toString(receive));
    if (colors.isSimilar(receive, "#fffcd901", 10)) {
        toast("领取多人包");
        click(1400, 1050);
        sleep(4000);
        var home = false;
        do {
            clickContinue();
            sleep(5000);
            home = colors.isSimilar(getPointColor(captureScreen(), 100, 100),"#ffbd003f",8);
        } while (!home);
    } else {
        backToHome();
    }
    main();
}

function backToHome() {
    var home = false;
    do {
        back();
        sleep(3000);
        var leftTop = getPointColor(captureScreen(), 100, 100);
        home = colors.isSimilar(leftTop, "#ffbd003f", 8);
    } while (!home);
}

function clickContinue() {
    click(2500, 1260);
}

function checkForResolution(x, y, img) {
    var width = img.getWidth();
    var height = img.getHeight();
    if (width < height) {
        var e = x;
        x = y;
        y = e;
    }

    return {
        positionX: x,
        positionY: y
    };
}

function getPointColor(img, x, y) {
    var data = checkForResolution(x, y, img);
    return images.pixel(img, data.positionX, data.positionY);
}